import { reqIphoneCode, reqLogout, reqRegisterUser, reqUserInfo, reqUserLogin } from '@/api/index';
import { setToken, getToken } from '@/utils/tokenUser';
const actions = {
    //获取验证码
    async getCode(context, phone) {
        let result = await reqIphoneCode(phone)
        if (result.code == 200) {
            console.log(result)
            return 'ok'
        } else {
            return Promise.reject(new Error('filer'))
        }
    },
    //用户注册
    async registerUser(context, data) {
        let result = await reqRegisterUser(data)
        if (result.code == 200) {
            return 'ok'
        } else {
            return Promise.reject(new Error('filer'))
        }
    },
    //用户登录
    async userLogin(context, data) {
        let result = await reqUserLogin(data)
        if (result.code == 200) {
            context.commit('USERLOGIN', result.data.token)
            return 'ok'
        } else {
            return Promise.reject(new Error('filer'))
        }
    },
    //登录成功后,获取用户信息
    async getUserInfo(context) {
        let result = await reqUserInfo()
        if (result.code == 200) {
            context.commit('GETUSERINFO', result.data)
            return 'ok'
        } else {
            return Promise.reject(new Error('filer'))
        }
    },
    //退出登录
    async logout(context) {
        let result = await reqLogout()
        if (result.code == 200) {
            //退出登录成功
            context.commit('LOGOUT')
            return 'ok'
        } else {
            return Promise.reject(new Error('file'))
        }
    }
}
const mutations = {
    LOGOUT(state) {
        //清除本地存储的token
        localStorage.removeItem("TOKEN");
        //清除用户
        state.userInfo = {};
        state.token = ''
    },
    GETUSERINFO(state, value) {
        //保存用户名
        state.userInfo = value
    },
    USERLOGIN(state, value) {
        //登录成功后，获取token，以后使用token向服务器获取用户信息
        state.token = value
        //保存到本地存储
        setToken(value)
    }
}
const state = {
    token: getToken(),
    userInfo: {},

}
const getters = {}
export default {
    namespaced: true,// 开启命名空间
    actions, mutations, state, getters
}